<template>
  <view class="info overflow-hidden pt-2 px-4">
    <image
      class="info-image"
      src="https://artist-eyes.obs.cn-south-1.myhuaweicloud.com/ppd/images/doctor.png"
      mode="widthFix"
    />
    <button
      v-if="isAgreed"
      open-type="getPhoneNumber"
      class="login-button mt-8"
      @getphonenumber="submitWXPhoneNumber"
    >
      微信一键登录
    </button>
    <button v-else class="login-button mt-8" @click="WXPhoneNumberLogin">微信一键登录</button>
    <button class="input-button mt-8" @click="phoneNumberLogin">手机号密码登录</button>
    <button class="input-button mt-8" @click="passwordLogin">用户名密码登录</button>
    <!-- 手机号输入框弹窗 -->
    <view v-if="showPhoneNumberModal" class="modal">
      <view class="modal-content">
        <text>请输入手机号：</text>
        <input v-model="phoneNumberInput" type="tel" placeholder="" />
        <text>请输入密码：</text>
        <input v-model="phonePasswordInput" type="safe-password" placeholder="" />
        <view class="btn-container{}">
          <button @click="submitPhoneNumberModel">提交</button>
          <button @click="closePhoneNumberModel">关闭</button>
        </view>
      </view>
    </view>
    <!-- 用户名密码弹窗 -->
    <view v-if="showPasswordModal" class="modal">
      <view class="modal-content">
        <text>请输入用户名：</text>
        <input v-model="usernameInput" type="text" placeholder="" />
        <text>请输入密码：</text>
        <input v-model="passwordInput" type="safe-password" placeholder="" />
        <view class="btn-container{}">
          <button @click="submitPasswordModal">提交</button>
          <button @click="closePasswordModal">关闭</button>
        </view>
      </view>
    </view>
    <view class="agreement-container">
      <view class="agreement-checkbox">
        <checkbox-group @change="handleAgreementChange">
          <label class="checkbox-label">
            <checkbox value="agree" :checked="isAgreed" color="#07C160" />
            <text class="agreement-text">我已阅读并同意</text>
          </label>
        </checkbox-group>
        <!-- 协议链接（可点击跳转） -->
        <text class="agreement-link" @click="navigateToAgreement">《微信手机号隐私保护指引》</text>
      </view>
    </view>
    <view class="cancel-login mt-8">
      <text @click="cancelLogin">取消登录</text>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import {
  postWXLoginAPI,
  loggedUserInfoAPI,
  getWXPhoneNumber,
  postUAPLoginAPI,
  postPAPLoginAPI,
} from '@/service/user/user'
import { useUserStore } from '@/store/user'

const userStore = useUserStore()
const userInfo = computed(() => userStore.userInfo)
const isLogined = computed(() => userStore.isLogined)

const showPhoneNumberModal = ref(false)
const showPasswordModal = ref(false)
const phoneNumberInput = ref('')
const phonePasswordInput = ref('')
const usernameInput = ref('')
const passwordInput = ref('')
const isAgreed = ref(false)

defineOptions({
  name: 'Login',
})

// 微信授权登录
function submitWXPhoneNumber(e) {
  console.log('WXPhoneNumberLogin', e)
  // 获取手机号
  if (e.detail.errMsg === 'getPhoneNumber:ok') {
    getWXPhoneNumber(e.detail.code).then((res) => {
      console.log('getWXPhoneNumber', res)
      const cellphone = res.phoneNumber
      // 微信登录账号
      postWXLoginAPI(cellphone)
        .then((response) => {
          console.log('登录成功:', response)
          // 保存 token 和用户信息到 UserStore
          userStore.setUserInfo({
            token: response.access_token, // 添加 token 信息到用户数据中
          })
          uni.showToast({
            title: '登录成功',
            icon: 'success',
            duration: 2000,
          })
          loggedUserInfoAPI().then((res) => {
            console.log('登录用户个人信息', res)
            userStore.setUserInfo({
              id: res.id,
              username: res.username,
              nickname: res.nickname,
              avatar: res.avatar,
              cellphone: res.cellphone,
              email: res.email,
              gender: res.gender,
              state: res.state,
              token: response.access_token,
            })
            // 返回上一级
            uni.navigateBack({
              delta: 1,
            })
          })
        })
        .catch((error) => {
          console.error('登录失败:', error)
          uni.showToast({
            title: '登录失败，请重试',
            icon: 'none',
          })
        })
    })
  } else {
    uni.showToast({
      title: '取消登录',
      icon: 'none',
    })
    console.log('getPhoneNumber失败', e)
  }
}

// 输入手机号密码登录
const submitPhoneNumberModel = () => {
  postPAPLoginAPI(phoneNumberInput.value, phonePasswordInput.value)
    .then((response) => {
      const access_token = response.access_token
      console.log('登录成功:', response)
      // 保存 token 和用户信息到 UserStore
      userStore.setUserInfo({
        token: access_token,
      })
      loggedUserInfoAPI()
        .then((res) => {
          console.log('登录用户个人信息', res)
          userStore.setUserInfo({
            id: res.id,
            username: res.username,
            nickname: res.nickname,
            avatar: res.avatar,
            cellphone: res.cellphone,
            email: res.email,
            gender: res.gender,
            state: res.state,
            token: response.access_token,
          })
          showPasswordModal.value = false
          // 返回上一级
          uni.navigateBack({
            delta: 1,
          })
        })
        .catch((error) => {
          console.error('登录失败:', error)
          uni.showToast({
            title: '登录失败，请重试',
            icon: 'none',
          })
        })
    })
    .catch((error) => {
      console.error('登录失败:', error)
      if (error.data.message == 'Incorrect cellphone') {
        uni.showToast({
          title: '登录失败，手机号错误或不存在',
          icon: 'none',
        })
      } else if (error.data.message == 'Incorrect password') {
        uni.showToast({
          title: '登录失败，密码错误',
          icon: 'none',
        })
      }
    })
}

// 输入用户名密码登录
const submitPasswordModal = () => {
  postUAPLoginAPI(usernameInput.value, passwordInput.value)
    .then((response) => {
      const access_token = response.access_token
      console.log('登录成功:', response)
      // 保存 token 和用户信息到 UserStore
      userStore.setUserInfo({
        token: access_token,
      })
      loggedUserInfoAPI()
        .then((res) => {
          console.log('登录用户个人信息', res)
          userStore.setUserInfo({
            id: res.id,
            username: res.username,
            nickname: res.nickname,
            avatar: res.avatar,
            cellphone: res.cellphone,
            email: res.email,
            gender: res.gender,
            state: res.state,
            token: response.access_token,
          })
          showPasswordModal.value = false
          // 返回上一级
          uni.navigateBack({
            delta: 1,
          })
        })
        .catch((error) => {
          console.error('登录失败:', error)
          uni.showToast({
            title: '登录失败，请重试',
            icon: 'none',
          })
        })
    })
    .catch((error) => {
      console.error('登录失败:', error)
      if (error.data.message == 'Incorrect username') {
        uni.showToast({
          title: '登录失败，用户名错误或不存在',
          icon: 'none',
        })
      } else if (error.data.message == 'Incorrect password') {
        uni.showToast({
          title: '登录失败，密码错误',
          icon: 'none',
        })
      }
    })
}

const WXPhoneNumberLogin = () => {
  if (!isAgreed.value) {
    uni.showToast({
      title: '请先阅读并同意协议',
      icon: 'none',
    })
  }
}

const phoneNumberLogin = () => {
  if (!isAgreed.value) {
    uni.showToast({
      title: '请先阅读并同意协议',
      icon: 'none',
    })
    return
  }
  showPhoneNumberModal.value = true
}

const closePhoneNumberModel = () => {
  showPhoneNumberModal.value = false
}

const passwordLogin = () => {
  if (!isAgreed.value) {
    uni.showToast({
      title: '请先阅读并同意协议',
      icon: 'none',
    })
    return
  }
  showPasswordModal.value = true
}

const closePasswordModal = () => {
  showPasswordModal.value = false
}

// 协议勾选状态变化
const handleAgreementChange = (e) => {
  isAgreed.value = e.detail.value.includes('agree')
}

// 跳转协议详情
const navigateToAgreement = () => {
  uni.navigateTo({
    url: '/pages/my/phonePrivacy',
  })
}

const cancelLogin = () => {
  // 返回上一级
  uni.navigateBack({
    delta: 1,
  })
}
</script>

<style lang="scss" scoped>
.info {
  display: flex;
  flex-direction: column;
  background: linear-gradient(180deg, rgba(215, 229, 247, 1) 0%, rgba(217, 234, 251, 0) 100%);
  height: 100vh;
  .login-button {
    width: 80%;
    background-color: #0075fe;
    border-radius: 12px;
    color: #eee;
    margin-top: 30px;
  }
  .input-button {
    width: 80%;
    background-color: #f3f3f3;
    border-radius: 12px;
    margin-top: 30px;
  }
  .info-image {
    width: 70%;
    height: auto;
    margin: 140px auto 0;
  }
}
.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.modal-content {
  background-color: white;
  padding: 20px;
  border-radius: 12px;
  width: 80%;
  text-align: center;
  input {
    height: 40px;
    line-height: 40px;
    background-color: #f3f3f3;
    font-size: 16px;
    margin-top: 10px;
    margin-bottom: 10px;
  }
  .btn-container {
    margin-top: 20px;
    display: flex;
    button {
      color: #fff;
      background-color: #0075fe;
      width: 48%;
    }
  }
}

.submit-btn {
  width: 80%;
  height: 44px;
  border-radius: 22px;
  color: white;
  font-size: 16px;
  border: none;
}

.agreement-container {
  padding: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;

  .agreement-checkbox {
    margin-top: 10px;
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    justify-content: center;
    z-index: 1;

    .checkbox-label {
      display: flex;
      align-items: center;

      checkbox {
        margin-right: 5px;
      }

      .agreement-text {
        font-size: 14px;
        color: #666;
      }
    }
  }
  .agreement-link {
    font-size: 14px;
    color: #576b95;
    text-decoration: underline;
  }
}

.cancel-login {
  margin-top: 10px;
  display: flex;
  justify-content: center;
  text {
    font-size: 16px;
  }
}
</style>
